<template>
  <div class="course-detail">
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="course" class="course-container">
      <!-- 上部分：课程简要信息 -->
      <div class="course-summary">
        <div class="course-brief">
          <div class="course-image" v-if="course.coverImage">
            <img :src="course.coverImage" :alt="course.title" />
          </div>
          <div class="course-info">
            <h1>{{ course.title }}</h1>
            <div class="course-meta">
              <div class="meta-left">
                <div class="meta-item">
                  <i class="fas fa-user"></i>
                  <span>讲师: {{ course.consultantName }}</span>
                </div>
                <div class="meta-item">
                  <i class="fas fa-folder"></i>
                  <span>分类: {{ course.categoryName }}</span>
                </div>
                <div class="meta-item" v-if="course.startTime">
                  <i class="fas fa-calendar-alt"></i>
                  <span>开课时间: {{ course.startTime }}</span>
                </div>
                <div class="meta-item">
                  <i class="fas fa-star"></i>
                  <span
                    v-if="course.score"
                    style="display: flex; align-items: center"
                  >
                    {{ course.score.toFixed(1) }} 分
                    <div style="display: flex; align-items: center">
                      <el-rate
                        :model-value="course.score"
                        disabled
                        disabled-void-color="#eee"
                        style="margin: 0 8px"
                      />
                      <span>{{ rateTexts[Math.round(course.score) - 1] }}</span>
                    </div>
                    <span style="color: #999; font-size: 12px"
                      >({{ course.reviewCount }}人评价)</span
                    >
                  </span>
                  <span v-else style="color: #999">暂无评价</span>
                </div>
              </div>
              <div class="meta-right">
                <div class="stat-item">
                  <i class="fas fa-heart"></i>
                  <span>{{ course.favoriteCount }}</span>
                </div>
                <div class="stat-item">
                  <i class="fas fa-comment"></i>
                  <span>{{ course.reviewCount }}</span>
                </div>
                <div class="stat-item">
                  <i class="fas fa-thumbs-up"></i>
                  <span>{{ course.likeCount }}</span>
                </div>
              </div>
            </div>
            <div class="course-intro">
              <h3>课程简介</h3>
              <p>{{ course.description }}</p>
            </div>
            <div class="course-actions">
              <div v-if="isCanEnroll" class="countdown-container">
                <div class="countdown-label">距离开课还有</div>
                <div class="countdown-time">
                  <span class="time-item">
                    <span class="time-value">{{ surplusDate.days }}</span>
                    <span class="time-unit">天</span>
                  </span>
                  <span class="time-item">
                    <span class="time-value">{{ surplusDate.hours }}</span>
                    <span class="time-unit">时</span>
                  </span>
                  <span class="time-item">
                    <span class="time-value">{{ surplusDate.minutes }}</span>
                    <span class="time-unit">分</span>
                  </span>
                  <span class="time-item">
                    <span class="time-value">{{ surplusDate.seconds }}</span>
                    <span class="time-unit">秒</span>
                  </span>
                </div>
              </div>
              <button v-else class="enroll-btn" @click="handleEnroll">
                {{ hasFavorite ? "继续学习" : "立即报名" }}
              </button>
              <button
                class="preview-btn"
                v-if="hasFavorite"
                @click="handleCancelEnroll"
              >
                取消报名
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 下部分：课程详情和评论 -->
      <div class="course-detail-content">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="课程详情" name="detail">
            <div class="rich-content" v-html="course.content"></div>
          </el-tab-pane>
          <el-tab-pane label="课程评论" name="comments">
            <!-- 排序选项 -->
            <div class="comment-sort">
              <el-radio-group
                v-model="sortType"
                @change="handleSortChange"
                size="small"
              >
                <el-radio-button label="newSort">最新</el-radio-button>
                <el-radio-button label="hotSort">最热</el-radio-button>
              </el-radio-group>
            </div>
            <div class="comment-list">
              <el-empty
                v-if="commentList.length === 0"
                description="暂无评论"
              />
              <template v-else>
                <div
                  v-for="item in commentList"
                  :key="item.id"
                  class="comment-item"
                >
                  <div class="comment-user">
                    <el-avatar :src="item.avatar" />
                    <div class="user-info">
                      <span class="nickname">{{ item.nickName }}</span>
                      <div class="rate-container">
                        <el-rate
                          :model-value="item.rating"
                          disabled
                          disabled-void-color="#eee"
                        />
                        <span style="color: #999; font-size: 12px"
                          >{{ rateTexts[item.rating - 1] }}</span
                        >
                      </div>
                    </div>
                    <span class="comment-time">{{
                      formatTime(item.reviewTime)
                    }}</span>
                  </div>
                  <div class="comment-content">{{ item.comment }}</div>
                  <div class="comment-actions">
                    <span
                      class="like-btn"
                      :class="{ active: item.isLike }"
                      @click="handleLike(item)"
                    >
                      <i class="fas fa-thumbs-up"></i>
                      <span>{{ item.likeCount }}</span>
                    </span>
                  </div>
                </div>

                <!-- 加载更多 -->
                <div v-if="hasMore" class="load-more">
                  <el-button link @click="loadMore">加载更多</el-button>
                </div>
              </template>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div v-else class="error-message">课程信息不存在或已被删除</div>
  </div>
</template>

<script setup lang="ts">
import { rateTexts } from "@/constant/rateTexts";
import {
  requestCourseInfo,
  type CourseInfoVO,
  queryComment,
  type CourseReviewVO,
  queryPublishComment,
} from "@/api/course";
import {
  addCourse,
  checkUserHasCourse,
  deleteByUserIdAndCourseId,
  type UserCourse,
} from "@/api/user-course";
import router from "@/router";
import { useUserStore } from "@/store";
import { ElMessage } from "element-plus";
import moment from "moment";
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import { useRoute } from "vue-router";
import { like, type CourseReviewLike } from "@/api/review";

const route = useRoute();
const courseId = route.params.id;
const loading = ref(true);
const course = ref<CourseInfoVO | null>(null);
const hasFavorite = ref(false);
const queryFavorite = () => {
  checkUserHasCourse({
    courseId: course.value?.id,
  }).then((res) => {
    hasFavorite.value = res;
  });
};
const isCanEnroll = ref(true);
const countDown = (time: string) => {
  const now = moment();
  const endTime = moment(time);
  const diff = endTime.diff(now, "seconds");
  isCanEnroll.value = diff > 0;
  return diff;
};
const timer = ref<number>();
const surplusDate = ref({
  days: "0",
  hours: "0",
  minutes: "0",
  seconds: "0",
});
// 开始距离开课时间倒计时
const startCountDown = () => {
  timer.value = setInterval(() => {
    const diff = countDown(course.value?.startTime as string);
    if (diff >= 0) {
      const duration = moment.duration(diff, "seconds");
      surplusDate.value = {
        days: Math.floor(duration.asDays()).toString().padStart(2, "0"),
        hours: duration.hours().toString().padStart(2, "0"),
        minutes: duration.minutes().toString().padStart(2, "0"),
        seconds: duration.seconds().toString().padStart(2, "0"),
      };
    } else {
      clearInterval(timer.value);
    }
  }, 1000);
};
onUnmounted(() => {
  clearInterval(timer.value);
});
const fetchCourseData = async () => {
  try {
    loading.value = true;
    const res = await requestCourseInfo(courseId as string);
    course.value = res;
    isCanEnroll.value = !moment(course.value?.startTime).isBefore(moment());
    queryFavorite();
    if (!moment(course.value?.startTime).isBefore(moment())) {
      startCountDown();
    }
  } catch (error) {
    console.error("获取课程详情失败:", error);
  } finally {
    loading.value = false;
  }
};
const userStore = useUserStore();
console.log(userStore.userInfo);

const handleEnroll = async () => {
  if (!userStore.userInfo?.userId) {
    ElMessage.warning("请先登录");
    router.push({
      path: "/login",
      query: {
        redirect: route.fullPath,
      },
    });
    return;
  }
  if (hasFavorite.value) {
    router.push({
      path: "/course-learning",
      query: {
        courseId: course.value?.id,
      },
    });
  } else {
    const params: Partial<UserCourse> = {
      courseId: course.value?.id,
      courseName: course.value?.title,
      consultantId: course.value?.consultantId,
      consultantName: course.value?.consultantName,
      categoryId: course.value?.categoryId,
      categoryName: course.value?.categoryName,
      coverImage: course.value?.coverImage,
      lastLearnTime: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    const res = await addCourse(params);
    if (res) {
      ElMessage.success("报名成功");
      router.push({
        path: "/course-learning",
        query: {
          courseId: course.value?.id,
        },
      });
    }
  }
};
const handleCancelEnroll = async () => {
  const res = await deleteByUserIdAndCourseId({
    courseId: course.value?.id,
  });
  if (res) {
    ElMessage.success("取消报名成功");
    queryFavorite();
  }
};
onMounted(() => {
  fetchCourseData();
});

// 评论相关
const activeTab = ref("detail");
const commentList = ref<CourseReviewVO[]>([]);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const hasMore = computed(() => commentList.value.length < total.value);
const sortType = ref<"newSort" | "hotSort">("newSort");

// 获取评论列表
const getCommentList = async (isLoadMore = false) => {
  try {
    const res = await queryPublishComment({
      courseId: Number(courseId),
      sortKey: sortType.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    });
    if (isLoadMore) {
      commentList.value.push(...res.records);
    } else {
      commentList.value = res.records;
    }
    total.value = res.total;
  } catch (error) {
    console.error("获取评论列表失败:", error);
  }
};

// 处理排序变化
const handleSortChange = () => {
  pageNum.value = 1;
  getCommentList();
};

// 加载更多
const loadMore = () => {
  pageNum.value++;
  getCommentList(true);
};

// 格式化时间
const formatTime = (time: string) => {
  return moment(time).format("YYYY-MM-DD HH:mm:ss");
};

// 监听 tab 切换
watch(activeTab, (newVal) => {
  if (newVal === "comments" && commentList.value.length === 0) {
    getCommentList();
  }
});

// 点赞评论
const handleLike = async (comment: CourseReviewVO) => {
  if (!userStore.userInfo?.userId) {
    ElMessage.warning("请先登录");
    router.push({
      path: "/login",
      query: {
        redirect: route.fullPath,
      },
    });
    return;
  }

  try {
    const params: CourseReviewLike = {
      reviewId: comment.id,
      userId: userStore.userInfo.userId,
    } as CourseReviewLike;

    const res = await like(params);
    if (res) {
      comment.likeCount = comment.likeCount + (comment.isLike ? -1 : 1);
      comment.isLike = !comment.isLike;
    }
  } catch (error) {
    console.error("点赞失败:", error);
  }
};
</script>

<style scoped>
.course-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading,
.error-message {
  text-align: center;
  margin: 50px 0;
  font-size: 18px;
}

.error-message {
  color: #dc3545;
}

.course-container {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 上部分：课程简要信息 */
.course-summary {
  padding: 30px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ddd;
  margin-bottom: 20px;
  text-align: left;
}

.course-brief {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.course-image {
  flex: 0 0 300px;
  max-width: 300px;
}

.course-image img {
  width: 100%;
  border-radius: 8px;
  height: 200px;
  object-fit: cover;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.course-info {
  flex: 1;
  min-width: 0;
}

.course-info h1 {
  margin: 0 0 15px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
  line-height: 1.4;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.meta-left {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.meta-right {
  display: flex;
  gap: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.meta-item i {
  color: #007bff;
  font-size: 16px;
}

.course-intro {
  margin-bottom: 20px;
  text-align: left;
}

.course-intro h3 {
  margin: 0 0 12px;
  color: #333;
  font-size: 16px;
  font-weight: 500;
}

.course-intro p {
  margin: 0;
  line-height: 1.6;
  color: #666;
  font-size: 14px;
}

.course-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.enroll-btn,
.preview-btn {
  padding: 12px 24px;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 16px;
}

.enroll-btn {
  background-color: #007bff;
  color: white;
  border: none;
}

.preview-btn {
  background-color: white;
  color: #007bff;
  border: 1px solid #007bff;
}

.enroll-btn:hover {
  background-color: #0056b3;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.preview-btn:hover {
  background-color: rgba(0, 123, 255, 0.1);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

/* 下部分：课程详情和评论 */
.course-detail-content {
  padding: 30px;
  text-align: left;
}

.course-detail-content h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
  position: relative;
  padding-bottom: 10px;
  text-align: left;
}

.course-detail-content h2::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 60px;
  height: 3px;
  background-color: #007bff;
}

.rich-content {
  line-height: 1.6;
  color: #444;
}

.rich-content :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 15px 0;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.rich-content :deep(p) {
  margin-bottom: 15px;
}

.rich-content :deep(h1, h2, h3, h4, h5, h6) {
  margin: 20px 0 10px;
  color: #333;
  font-weight: 600;
}

.rich-content :deep(ul, ol) {
  padding-left: 20px;
  margin-bottom: 15px;
}

.rich-content :deep(li) {
  margin-bottom: 8px;
}

.countdown-container {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px 24px;
  text-align: center;
  border: 1px solid #e0e0e0;
}

.countdown-label {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.countdown-time {
  display: flex;
  gap: 12px;
  justify-content: center;
  align-items: center;
}

.time-item {
  display: flex;
  align-items: baseline;
  gap: 2px;
}

.time-value {
  background: #007bff;
  color: white;
  padding: 6px 10px;
  border-radius: 4px;
  font-size: 20px;
  font-weight: 600;
  min-width: 40px;
  display: inline-block;
  text-align: center;
}

.time-unit {
  color: #666;
  font-size: 14px;
  margin-left: 2px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 14px;
}

.stat-item i {
  color: #007bff;
  font-size: 16px;
}

.stat-item:hover {
  color: #007bff;
}

@media (max-width: 768px) {
  .course-brief {
    flex-direction: column;
  }

  .course-image {
    flex: none;
    max-width: none;
    margin-bottom: 20px;
  }

  .course-info h1 {
    font-size: 20px;
  }

  .course-meta {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .meta-right {
    width: 100%;
    justify-content: space-around;
    padding-top: 10px;
    border-top: 1px solid #e0e0e0;
  }

  .countdown-time {
    gap: 8px;
  }

  .time-value {
    font-size: 16px;
    padding: 4px 8px;
    min-width: 32px;
  }

  .time-unit {
    font-size: 12px;
  }

  .meta-item :deep(.el-rate) {
    margin: 4px 0 !important;
  }
}

/* 评论列表样式 */
.comment-list {
  margin-top: 20px;
}

.comment-item {
  padding: 20px;
  border-radius: 8px;
  background: #f8f9fa;
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.comment-item:hover {
  background: #f0f2f5;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.comment-user {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.nickname {
  font-weight: 600;
  color: #333;
  font-size: 15px;
}

.comment-time {
  color: #999;
  font-size: 13px;
  margin-left: auto;
}

.comment-content {
  color: #333;
  line-height: 1.6;
  margin: 12px 0;
  font-size: 14px;
  padding: 0 4px;
}

.load-more {
  text-align: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.rate-container {
  display: flex;
  align-items: center;
}

:deep(.el-empty) {
  padding: 40px 0;
  background: #f8f9fa;
  border-radius: 8px;
  margin: 20px 0;
}

:deep(.el-empty__description) {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

:deep(.el-tabs__nav) {
  margin-bottom: 20px;
}

.comment-sort {
  margin-bottom: 20px;
  text-align: right;
}

.comment-actions {
  display: flex;
  align-items: center;
  gap: 20px;
  padding-top: 12px;
  margin-top: 12px;
  border-top: 1px solid #eee;
}

.like-btn {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.like-btn:hover {
  background: #e6f3ff;
  color: #007bff;
}

.like-btn.active {
  color: #007bff;
}

.like-btn i {
  font-size: 16px;
}

.meta-item :deep(.el-rate) {
  display: inline-flex;
  vertical-align: text-bottom;
}

.meta-item :deep(.el-rate__icon) {
  font-size: 16px;
  margin-right: 4px;
}
</style>
